package com.zxb.core.dds;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.zaxxer.hikari.HikariDataSource;

import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;

import javax.annotation.Nonnull;

/**
 * @author Zxb
 */
@Component
@AllArgsConstructor
public class DataSourceUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(@Nonnull ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    private JdbcTemplate jdbcTemplate;

    public void change(String key) {
        if (StrUtil.isBlank(key)) {
            DynamicDataSource.clear();
            return;
        }

        if (DynamicDataSource.dataSourceMap.containsKey(key)) {
            DynamicDataSource.change(key);
            return;
        }
        DynamicDataSource.clear();
        Integer count = jdbcTemplate.queryForObject("select count(1) from wm_settle_datasource where code = ?", Integer.class, key);
        if (count == null || count == 0) {
            return;
        }
        Map<String, Object> map = jdbcTemplate.queryForMap("select * from wm_settle_datasource where code = ?", key);
        HikariDataSource dataSource = DataSourceBuilder.create()
                .type(HikariDataSource.class)
                .url((String) map.get("jdbc_url"))
                .username((String) map.get("username"))
                .password((String) map.get("passwd"))
                .driverClassName((String) map.get("driver_class_name"))
                .build();
        DynamicDataSource.configDs(dataSource);
        DynamicDataSource.dataSourceMap.put(key, dataSource);
        DynamicDataSource ds = (DynamicDataSource) context.getBean("dynamicDataSource");
        ds.afterPropertiesSet();
        DynamicDataSource.change(key);
    }

    public void clear() {
        DynamicDataSource.clear();
    }
}
